const Router = require("koa-router");
const mongoose = require("mongoose");
const fs = require("fs");
let router = new Router();
const jwt = require("jsonwebtoken");
const path = require("path");

router.get("/insertallgoodsinfo", async ctx => {
  fs.readFile("./newGoods.json", "utf8", (err, data) => {
    if (err) {
      console.log("数据读取错误");
    }
    data = JSON.parse(data);
    let count = 0;
    let Goods = mongoose.model("Good");
    data.map(value => {
      let newGoods = new Goods(value);
      newGoods
        .save()
        .then(() => {
          count++;
          console.log("成功" + count);
        })
        .catch(err => {
          console.log(err);
        });
    });
    console.log(count);
  });
  ctx.body = "开始导入数据";
});

router.get("/insertAllCategory", async ctx => {
  fs.readFile("./data_json/category.json", "utf8", (err, data) => {
    data = JSON.parse(data);
    let saveCount = 0;
    let Category = mongoose.model("Category");
    data.RECORDS.map(value => {
      console.log(value);
      let newData = new Category(value);
      newData
        .save()
        .then(() => {
          saveCount++;
          console.log("插入成功" + saveCount);
        })
        .catch(err => {
          console.log("插入失败" + err);
        });
    });
  });
  ctx.body = "插入数据";
});

router.get("/insertAllCategorySub", async ctx => {
  fs.readFile("./data_json/category_sub.json", "utf8", (err, data) => {
    data = JSON.parse(data);
    let saveCount = 0;
    let CategorySub = mongoose.model("CategorySub");
    data.RECORDS.map(value => {
      console.log(value);
      let newData = new CategorySub(value);
      newData
        .save()
        .then(() => {
          saveCount++;
          console.log("插入成功" + saveCount);
        })
        .catch(err => {
          console.log("插入失败" + err);
        });
    });
  });
  ctx.body = "导入子类数据";
});

router.get("/main", async ctx => {
  console.log("首页请求");
  const Goods = mongoose.model("Good");
  var num = Math.round(Math.random() * 600);
  let data = {};
  let result = await Goods.find()
    .skip(num)
    .limit(58);
  data.slides = result.slice(0, 3);
  data.recommend = result.slice(3, 20);
  data.floor1 = result.slice(20, 26);
  data.floor2 = result.slice(26, 32);
  data.floor3 = result.slice(32, 38);
  data.floorName = {
    floor3: "猜你喜欢",
    floor2: "近期爆款",
    floor1: "火爆抢购"
  };
  data.hotGoods = result.slice(38, 58);
  data.advertesPicture = {
    PICTURE_ADDRESS:
      "http://images.baixingliangfan.cn/advertesPicture/20180404/20180404085441_850.gif"
  };
  data.category = [
    {
      mallCategoryId: "1",
      mallCategoryName: "新鲜水果",
      image:
        "http://images.baixingliangfan.cn/firstCategoryPicture/20180408/20180408111959_2837.png"
    },
    {
      mallCategoryId: "2",
      mallCategoryName: "中外名酒",
      image:
        "http://images.baixingliangfan.cn/firstCategoryPicture/20180408/20180408112010_4489.png"
    },
    {
      mallCategoryId: "3",
      mallCategoryName: "营养奶品",
      image:
        "http://images.baixingliangfan.cn/firstCategoryPicture/20180408/20180408113102_1595.png"
    },
    {
      mallCategoryId: "5",
      mallCategoryName: "食品饮料",
      image:
        "http://images.baixingliangfan.cn/firstCategoryPicture/20180408/20180408113048_1276.png"
    },
    {
      mallCategoryId: "4",
      mallCategoryName: "个人护理",
      image:
        "http://images.baixingliangfan.cn/firstCategoryPicture/20180408/20180408112053_8191.png"
    }
  ];
  ctx.body = {
    code: 200,
    data: data
  };
});

// 获取商品详情信息接口
router.post("/getDetailGoodsInfo", async ctx => {
  try {
    let goodsId = ctx.request.body.goodsId;
    const Goods = mongoose.model("Good");
    let result = await Goods.findOne({ ID: goodsId });
    ctx.body = {
      code: 200,
      message: result
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    };
  }
});

// 获取商品大类信息
router.get("/categoryList", async ctx => {
  try {
    const Category = mongoose.model("Category");
    let result = await Category.find();
    ctx.body = {
      code: 200,
      message: result
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    };
  }
});

// 获取商品小类数据
router.post("/categorySubList", async ctx => {
  try {
    let categoryId = ctx.request.body.categorySubId;
    const Category = mongoose.model("CategorySub");
    let result = await Category.find({ MALL_CATEGORY_ID: categoryId });
    ctx.body = {
      code: 200,
      message: result
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    };
  }
});

// 根据子类id获取商品分页数据
router.post("/getGoodsListByCategorySubId", async ctx => {
  try {
    let categoryId = ctx.request.body.categorySubId;
    console.log(categoryId);
    let page = ctx.request.body.page; // 当前所处页数
    let num = 10; // 每页要显示的子类商品数目
    let start = (page - 1) * num; // 每页商品开始位置
    const Goods = mongoose.model("Good");
    let result = await Goods.find({ SUB_ID: categoryId })
      .skip(start) // limit() 方法限制从数据库查找的商品数目
      .limit(num); // skip() 方法跳过 start 个商品，从 start+1开始读取数据
    ctx.body = {
      code: 200,
      message: result
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    };
  }
});

// 提交评论
router.post("/comment", async ctx => {
  // console.log(ctx.request.body);
  const commentModel = mongoose.model("comment");
  let user = await jwt.verify(
    ctx.request.headers.authorization.split(" ")[1],
    "my_token"
  );
  let isNew = true;
  let oriResult;
  // 看数据库中有没有这个商品的评论
  await commentModel
    .findOne({ goodsId: ctx.request.body.goodsId })
    .then(result => {
      if (result) {
        isNew = false;
        oriResult = result;
        // console.log(result);
        // 有就更新
      } else {
        console.log("没找到");
      }
    });
  if (!isNew) {
    console.log("更新评论");
    let commentArray = [];
    // 取出原评论
    commentArray = commentArray.concat(oriResult.comment);
    // 增加评论
    commentArray.unshift({
      username: user.name,
      comment: ctx.request.body.comment,
      count: commentArray.length + 1
    });
    // 更新评论
    await commentModel.update(
      // 查找条件
      { goodsId: ctx.request.body.goodsId },
      // 更新数据
      { comment: commentArray },
      function(err) {
        if (err) {
          // console.log("更新出错");
          ctx.body = {
            code: 500,
            message: "增加评论出错"
          };
        } else {
          // console.log("更新成功");
          ctx.body = {
            code: 200,
            message: "增加评论成功"
          };
        }
      }
    );
  }
  if (isNew) {
    console.log("增加评论");
    // 没有就增加
    let commentArray = [];
    commentArray.unshift({
      username: user.name,
      comment: ctx.request.body.comment,
      count: 1
    });
    // console.log(commentArray);
    let newcomment = new commentModel({
      goodsId: ctx.request.body.goodsId,
      comment: commentArray,
      userName: Date.now(),
      goodsName: Date.now() + 1
    });
    console.log(newcomment);
    await newcomment
      .save()
      .then(() => {
        console.log("增加新的商品评论成功");
        ctx.body = {
          code: 200,
          message: "评论提交成功"
        };
      })
      .catch(err => {
        console.log("增加新的商品评论出错了" + err);
        ctx.body = {
          code: 500,
          message: "增加评论出错"
        };
      });
  }
});

// 查找商品评论
router.post("/getComment", async ctx => {
  const commentModel = mongoose.model("comment");
  console.log("这是商品id");
  console.log(ctx.request.body.goodsId);
  let comment = [];
  await commentModel
    .findOne({ goodsId: ctx.request.body.goodsId })
    .then(result => {
      console.log("查找评论");
      console.log(result);
      if (result) {
        comment = result.comment;
      }
    });
  ctx.body = {
    code: 200,
    message: "获取商品评论成功",
    comment: comment
  };
});

// 提交搜索关键词
router.post("/postkeyword", async ctx => {
  console.log(ctx.request.body);
  const keyWord = mongoose.model("keyword");
  let newword = false;
  let number;
  await keyWord.findOne({ word: ctx.request.body.keyword }).then(result => {
    if (result) {
      console.log("查找搜索词成功");
      number = result.num + 1;
    } else {
      console.log("没找到");
      newword = true;
    }
  });
  if (!newword) {
    await keyWord.update(
      { word: ctx.request.body.keyword },
      { num: number },
      function(err) {
        if (err) {
          console.log("搜索词更新次数出错");
          ctx.body = {
            code: 500,
            message: "服务器出错"
          };
        } else {
          console.log("搜索词更新次数成功");
          ctx.body = {
            code: 200,
            message: "搜索词提交成功"
          };
        }
      }
    );
  }
  if (newword) {
    var newkey = new keyWord({
      word: ctx.request.body.keyword,
      num: 1
    });
    await newkey.save().then(() => {
      console.log("搜索词新建成功");
      ctx.body = {
        code: 200,
        message: "搜索词提交成功"
      };
    });
  }
});

// 查找热门搜索词
router.get("/gethotword", async ctx => {
  const keyWord = mongoose.model("keyword");
  var arr = await keyWord.find();
  console.log(arr);
  arr.sort((a, b) => {
    return b.num - a.num;
  });
  // 最多给20个热门搜索词
  arr.splice(19, arr.length - 20);
  ctx.body = {
    code: 200,
    hotword: arr
  };
});

// 根据关键词搜索商品信息
router.post("/getGoodsInfoByKeyWord", async ctx => {
  // console.log("搜索来了");

  let keyword = ctx.request.body.keyWord;
  console.log(ctx.request.body.keyWord);
  const Goods = mongoose.model("Good");
  let result = await Goods.find();
  let goodsNeed = [];
  result.map(value => {
    if (value.NAME.indexOf(keyword) >= 0) {
      goodsNeed.push(value);
    }
  });
  ctx.body = {
    code: 200,
    message: goodsNeed
  };
});

// 提交历史订单
router.post("/postCart", async ctx => {
  let isNewCart = true;
  const HistoryModel = mongoose.model("cart");
  let newCart = ctx.request.body; // 要提交的订单
  let cartFind;
  console.log(newCart);
  let newHistoryCart = new HistoryModel(newCart);
  await HistoryModel.findOne({ userName: newCart.userName }).then(result => {
    if (result) {
      console.log("数据库中存在历史订单");
      isNewCart = false;
      cartFind = result.cart;
    }
  });
  // 如果数据库中存在这个用户的历史订单 更新
  if (!isNewCart) {
    await HistoryModel.update(
      { userName: newCart.userName },
      { cart: newCart.cart.concat(cartFind) },
      function(err) {
        if (err) {
          ctx.body = {
            code: 500,
            message: "服务器出错"
          };
        } else {
          ctx.body = {
            code: 200,
            message: "订单提交成功"
          };
        }
      }
    );
  }
  // 新的历史订单则保存
  if (isNewCart) {
    await newHistoryCart.save();
    ctx.body = {
      code: 200,
      message: "订单提交成功"
    };
  }
});

// 查找历史订单
router.get("/getHistoryCart", async ctx => {
  let user = await jwt.verify(
    ctx.request.headers.authorization.split(" ")[1],
    "my_token"
  );
  console.log(user);
  const HistoryModel = mongoose.model("cart");
  await HistoryModel.findOne({ userName: user.name }).then(result => {
    if (result) {
      console.log("这是历史订单");
      console.log(result.cart);
      ctx.body = {
        code: 200,
        message: "订单查找成功",
        cart: result.cart
      };
    } else {
      ctx.body = {
        code: 200,
        message: "您没有历史订单"
      };
    }
  });
});

// 删除历史订单
router.get("/deleteCart", async ctx => {
  let user = await jwt.verify(
    ctx.request.headers.authorization.split(" ")[1],
    "my_token"
  );
  const HistoryModel = mongoose.model("cart");
  await HistoryModel.remove({ userName: user.name }).then(result => {
    console.log(result);
    ctx.body = {
      code: 200,
      message: "历史订单删除成功"
    };
  });
});

module.exports = router;
